package web;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import mongo.ClassDAO;
import mongo.ItemDAO;
import mongo.TopicItemDAO;

import org.apache.struts2.ServletActionContext;

import tool.DateUtils;
import tool.FileUtils;
import tool.Word;
import vo.ClassItem;
import vo.Item;
import vo.Log;
import vo.Source;
import vo.Topic;
import vo.TopicItem;
import vo.User;
import vo.UserTopic;
import business.LogService;
import business.SourceService;
import business.TopicService;
import business.UserService;
import business.UserTopicService;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Preparable;

import constant.Constant;

@SuppressWarnings("unchecked")
public class MyYuqingAction implements Preparable {
	private List<Item> items;
	private List<Topic> topics;
	private List<UserTopic> userTopics;
	private UserTopicService userTopicService;
	private TopicService topicService;
	private LogService logService;
	private SourceService sourceService;
	private UserService userService;
	private User curUser;

	// 分页使用的变量
	private int curPage = -1;
	private int pageSize = 8;
	private int totalPage;

	List<Item> myLast10Items = new ArrayList<Item>();// 我关注的最近10天的topic10
	List<Item> myYesterdayItems = new ArrayList<Item>();// 我关注的最近24小时的topic10
	private int topicSize;// 主题总数
	private int itemSize;// 舆情总数
	private int yesterdaySize;// 24小时新增舆情个数
	private int nonRead;

	private List<String> summaries;
	private String summary;

	private String keyword;
	private String sourceId;
	private String startDate;
	private String endDate;

	private String id;
	private String url;
	private List<Source> sources;

	private ArrayList<ArrayList<Item>> itemId_items = new ArrayList<ArrayList<Item>>();

	// 按照topic展示舆情
	private String topicId;

	private int redirectId;// 重新定位到的趋势

	// 标签云
	private ArrayList<String> keywords;

	public String home() {

		/*** 2. 用户关注：话题总数，舆情总数 ***/
		try {
			String homeFileName = Constant.root + curUser.getId() + "/home.txt";
			System.out.println(homeFileName);
			String homeContent = FileUtils.readFile(homeFileName, "utf-8");
			String lines[] = homeContent.split("\n");
			topicSize = Integer.parseInt(lines[0].split(":")[1]);
			itemSize = Integer.parseInt(lines[1].split(":")[1]);
			nonRead = Integer.parseInt(lines[2].split(":")[1]);
			String summaryTime = lines[3].split(":")[1];
			yesterdaySize = Integer.parseInt(lines[4].split(":")[1]);

			String yesterdayTop10 = FileUtils.readFile(Constant.root + curUser.getId() + "/yesterday_top10.txt", "utf-8");
			String last10DayTop10 = FileUtils.readFile(Constant.root + curUser.getId() + "/last10Day_top10.txt", "utf-8");
			// 昨天10大，24小时10大
			if (yesterdayTop10.length() > 0) {
				String[] yesterdayLines = yesterdayTop10.split("#");
				for (String line : yesterdayLines) {
					System.out.println("line:" + line);
					String items[] = line.split("@");
					if (items.length == 3) {
						Item item = new Item();
						item.setTitle(items[0]);
						item.setType(items[1]);
						item.setPubTime(DateUtils.str2Date(items[2]));
						// item.setContent(items[3]);
						this.myYesterdayItems.add(item);
					}
				}
			}
			if (last10DayTop10.length() > 0) {
				String[] last10DayLines = last10DayTop10.split("#");
				for (String line : last10DayLines) {
					String items[] = line.split("@");
					if (items.length == 3) {
						Item item = new Item();
						item.setTitle(items[0]);
						item.setType(items[1]);
						item.setPubTime(DateUtils.str2Date(items[2]));
						// item.setContent(items[3]);
						this.myLast10Items.add(item);
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return Action.SUCCESS;
	}

	// 舆情阅读
	public String listMyYuqing() {
		// 一些初始化
		sources = new ArrayList<Source>();
		items = new ArrayList<Item>();

		// 检索：下拉列表的文字
		sources = sourceService.getAllSources();

		// 话题跳转标记
		redirectId = 0;
		// 分页变量
		if (curPage == -1)
			curPage = 1;

		System.out.println("检索条件:" + startDate + "," + endDate + "," + sourceId);
		System.out.println("topicId:" + topicId);

		try {
			/*********************************** 显示舆情条目 ***************************************/
			// 检索所有的舆情
			if (topicId == null) {
				if (sourceId != null && sourceId.equals("0"))
					sourceId = null;
				int totalCount = ItemDAO.getTotalCountByCondition(startDate, endDate, sourceId);
				if (totalCount % pageSize == 0)
					totalPage = totalCount / pageSize;
				else
					totalPage = totalCount / pageSize + 1;
				items = ItemDAO.getAllItemsByCondition((curPage - 1) * pageSize, pageSize, startDate, endDate, sourceId);
				System.out.println("检索出来几个：" + items.size());
				for (Item item : items) {
					System.out.println("所有舆情：" + item);
				}
				System.out.println("curPage/totalPage:" + curPage / totalPage);
			}
			// 只检索特定topicId的舆情
			else {
				if (sourceId != null && sourceId.equals("0"))
					sourceId = null;
				int totalCount = TopicItemDAO.getTotalCountByCondition(startDate, endDate, sourceId, topicId);
				if (totalCount % pageSize == 0)
					totalPage = totalCount / pageSize;
				else
					totalPage = totalCount / pageSize + 1;
				System.out.println("检索条件：" + startDate + "," + endDate + "," + sourceId + "," + topicId);
				List<TopicItem> tis = TopicItemDAO.getAllByCondition((curPage - 1) * pageSize, pageSize, startDate, endDate, sourceId, topicId);
				for (TopicItem ti : tis) {
					String itemId = ti.getItemId();
					System.out.println("找itemId:---" + itemId + "----");
					System.out.println("---" + ti.getSource() + "," + ti.getItemId() + "," + ti.getTopicId() + "," + ti.getType() + "," + ti.getPubTime() + "---");
					Item item = ItemDAO.getById(itemId);
					System.out.println("找到没：" + item);
					items.add(item);
				}
				System.out.println("检索出来几个：" + items.size());
				for (Item item : items) {
					System.out.println("所有舆情：" + item);
				}
				System.out.println("curPage/totalPage:" + curPage + "/" + totalPage);
			}

			for (Item item : items) {
				// [重新封装]
				Source source = sourceService.getById(Long.parseLong(item.getSource()));
				item.setSource(source.getName());

				/******************************** 相似舆情 ********************************/
				// 找到item所在的类
				List<ClassItem> cis = ClassDAO.getByItemId(item.getId());
				if (cis == null || cis.size() == 0)
					continue;
				ClassItem ci = cis.get(0);// TODO:其实，一个item可以属于很多类，这里暂时先取一个
				String itemIds[] = ci.getItemIds().split("_");
				ArrayList<Item> simItems = new ArrayList<Item>();
				int count = 0;
				// 遍历同class的其他item
				for (String itemId : itemIds) {
					count++;
					// 只最多显示4个
					if (count < 4)
						if (!itemId.equals(item.getId())) {
							// 对于非本itemId的其他相似ID
							Item tmp = ItemDAO.getById(itemId);
							System.out.println("tmp.getSource():" + tmp.getSource());
							// 【重新封装】source->sourceName,content->topicItem.content
							Source simSource = sourceService.getById(Long.parseLong(tmp.getSource()));
							tmp.setSource(simSource.getName());
							simItems.add(tmp);
						}
				}
				itemId_items.add(simItems);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return Action.SUCCESS;

	}

	public String itemLog() {
		System.out.println("item id:" + id);
		System.out.println("url:" + url);
		Log log = new Log();
		log.setDttm(new Date());
		log.setUser(curUser);
		log.setMessage(String.valueOf(id));
		log.setType("read");
		logService.addLog(log);
		return "itemLog";
	}

	public String searchItems() {
		System.out.println("search:" + keyword + "," + sourceId);
		System.out.println("date:" + startDate + "," + endDate);
		return "searchItems";

	}

	// 主题分析,加上标签云
	public String listMyYuqing1() {
		System.out.println("yuqing1:" + topicId);
		redirectId = 1;
		this.keywords = new ArrayList<String>();
		// 没有任何主题
		if (topicId == null || topicId.length() == 0) {
			List<Topic> tmp=topicService.getAll();
			for(Topic topic:tmp)
				this.keywords.add(topic.getName());
		}
		// 有特定主题
		else {
			this.topics = topicService.getAll();
			Topic tmp = topicService.getById(Long.parseLong(topicId));
			String[] words = tmp.getKeywords().split(";");
			for (String word : words)
				this.keywords.add(word);
		}
		return Action.SUCCESS;
	}

	// 趋势分析
	public String listMyYuqing2() {
		redirectId = 2;
		System.out.println("yuqing2");
		System.out.println("topicId:" + topicId);
		return Action.SUCCESS;
	}

	// 媒体分析
	public String listMyYuqing3() {
		redirectId = 3;
		System.out.println("yuqing3");
		return Action.SUCCESS;
	}

	public String summaryList() {
		String homeFileName = Constant.root + curUser.getId() + "/home.txt";
		String fileContent = FileUtils.readFile(homeFileName, "utf-8");
		String timeStr = fileContent.split("\n")[3].split(":")[1];// 第三行的内容是时间段
		System.out.println("timeStr:" + timeStr);
		Date startDate = DateUtils.str2Date(timeStr.split("@")[0] + " 00:00:00");
		Date endDate = DateUtils.str2Date(timeStr.split("@")[1] + " 00:00:00");
		int totalCount = DateUtils.getDayDistance(endDate, startDate);
		System.out.println("startDate:" + startDate);
		System.out.println("endDate:" + endDate);
		System.out.println("totalCount:" + totalCount);
		// 分页代码
		if (curPage == -1 || curPage == 0)
			curPage = 1;
		if (totalCount % pageSize == 0)
			totalPage = totalCount / pageSize;
		else
			totalPage = totalCount / pageSize + 1;
		// 检索list
		System.out.println("summaryList:" + curPage + "," + pageSize);
		summaries = new ArrayList<String>();
		for (int i = 0; i < pageSize; i++) {
			Date tmp = DateUtils.str2Date(DateUtils.addDay(startDate, (curPage - 1) * pageSize + i));
			if (tmp.before(DateUtils.str2Date(DateUtils.addDay(endDate, 1))))
				this.summaries.add(DateUtils.date2DateStr(tmp, "-") + "简报");
		}

		return Action.SUCCESS;
	}

	// 舆情简报
	public String summaryDetail() {
		System.out.println("summary:" + summary);
		summary = summary.substring(0, 10);
		System.out.println("summary:" + summary);
		String summaryFile = Constant.root + curUser.getId() + "/yesterday_top10.txt";// TODO:dummy
		// String summaryFile=Constant.root + curUser.getId() +
		// "/summary/"+summary+".txt";//TODO:real
		String yesterdayTop10 = FileUtils.readFile(summaryFile, "utf-8");
		// 昨天10大，24小时10大
		String[] yesterdayLines = yesterdayTop10.split("#");
		for (String line : yesterdayLines) {
			System.out.println("line:" + line);
			String items[] = line.split("@");
			if (items.length < 3)
				continue;
			Item item = new Item();
			item.setTitle(items[0]);
			item.setType(items[1]);
			item.setPubTime(DateUtils.str2Date(items[2]));
			// item.setContent(items[3]);
			this.myYesterdayItems.add(item);
		}
		return Action.SUCCESS;
	}

	// 舆情简报
	public String exportSummary() {
		System.out.println("导出summary");
		System.out.println("summary:" + summary);
		String summaryFile = Constant.root + curUser.getId() + "/yesterday_top10.txt";// TODO:dummy
		String summaryWord = Constant.root + curUser.getId() + "/yesterday_top10.doc";// TODO:dummy
		// String summaryFile=Constant.root + curUser.getId() +
		// "/summary/"+summary+".txt";//TODO:real
		String yesterdayTop10 = FileUtils.readFile(summaryFile, "utf-8");
		try {
			Word.writeWord(summaryWord, yesterdayTop10);
		} catch (Exception e) {
			e.printStackTrace();
		}
		HttpServletResponse response = null;
		ServletOutputStream out = null;
		InputStream is = null;
		byte[] bytes = null;
		try {
			is = new BufferedInputStream(new FileInputStream(summaryWord)); // mid.jpg图片要与HelloJava.java同在一目录下
			response = ServletActionContext.getResponse();
			response.setContentType("application/msword");
			out = response.getOutputStream();
			bytes = new byte[1024];
			while (-1 != is.read(bytes)) {
				out.write(bytes);
			}
			// 强制刷新输出流
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			bytes = null;
		}

		return null;
	}

	// 媒体分析
	public String yuqingDispatcher() {
		System.out.println("redirectId:" + redirectId);
		System.out.println("topicId:" + topicId);
		System.out.println("yuqing dispatcher");
		if (redirectId == 0)
			return "redirect";
		if (redirectId == 1)
			return "redirect1";
		if (redirectId == 2)
			return "redirect2";
		if (redirectId == 3)
			return "redirect3";

		return Action.SUCCESS;
	}

	public void prepare() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();
		String username = (String) session.get("username");
		curUser = userService.getByLoginName(username);
		System.out.println("curUser.getLoginName():" + curUser.getLoginName());
		long userId = curUser.getId();
		userTopics = userTopicService.getUserTopicsByUserId(userId);

	}

	public List<Item> getItems() {
		return items;
	}

	public void setItems(List<Item> items) {
		this.items = items;
	}

	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public void setUserTopicService(UserTopicService userTopicService) {
		this.userTopicService = userTopicService;
	}

	public List<UserTopic> getUserTopics() {
		return userTopics;
	}

	public void setUserTopics(List<UserTopic> userTopics) {
		this.userTopics = userTopics;
	}

	public User getCurUser() {
		return curUser;
	}

	public void setCurUser(User curUser) {
		this.curUser = curUser;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public List<Topic> getTopics() {
		return topics;
	}

	public void setTopics(List<Topic> topics) {
		this.topics = topics;
	}

	public void setTopicService(TopicService topicService) {
		this.topicService = topicService;
	}

	public List<Item> getMyLast10Items() {
		return myLast10Items;
	}

	public void setMyLast10Items(List<Item> myLast10Items) {
		this.myLast10Items = myLast10Items;
	}

	public List<Item> getMyYesterdayItems() {
		return myYesterdayItems;
	}

	public void setMyYesterdayItems(List<Item> myYesterdayItems) {
		this.myYesterdayItems = myYesterdayItems;
	}

	public int getTopicSize() {
		return topicSize;
	}

	public void setTopicSize(int topicSize) {
		this.topicSize = topicSize;
	}

	public int getItemSize() {
		return itemSize;
	}

	public void setItemSize(int itemSize) {
		this.itemSize = itemSize;
	}

	public int getYesterdaySize() {
		return yesterdaySize;
	}

	public void setYesterdaySize(int yesterdaySize) {
		this.yesterdaySize = yesterdaySize;
	}

	public int getNonRead() {
		return nonRead;
	}

	public void setNonRead(int nonRead) {
		this.nonRead = nonRead;
	}

	public TopicService getTopicService() {
		return topicService;
	}

	public List<String> getSummaries() {
		return summaries;
	}

	public void setSummaries(List<String> summaries) {
		this.summaries = summaries;
	}

	public String getSummary() {
		return summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getSourceId() {
		return sourceId;
	}

	public void setSourceId(String sourceId) {
		this.sourceId = sourceId;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public ArrayList<ArrayList<Item>> getItemId_items() {
		return itemId_items;
	}

	public void setItemId_items(ArrayList<ArrayList<Item>> itemId_items) {
		this.itemId_items = itemId_items;
	}

	public String getTopicId() {
		return topicId;
	}

	public void setTopicId(String topicId) {
		this.topicId = topicId;
	}

	public int getRedirectId() {
		return redirectId;
	}

	public void setRedirectId(int redirectId) {
		this.redirectId = redirectId;
	}

	public List<Source> getSources() {
		return sources;
	}

	public void setSources(List<Source> sources) {
		this.sources = sources;
	}

	public void setSourceService(SourceService sourceService) {
		this.sourceService = sourceService;
	}

	public ArrayList<String> getKeywords() {
		return keywords;
	}

	public void setKeywords(ArrayList<String> keywords) {
		this.keywords = keywords;
	}

}